﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MDT.LifeSewagePlatform.Conmmon
{
    /**
    * 命名空间: MDT.LifeSewagePlatform.Conmmon
    *
    * 功 能： N/A
    * 类 名： ActionAuthrizaFilterAttribute
    *
    * Ver 变更日期 负责人 变更内容
    * ───────────────────────────────────
    * V0.01 2022/2/14 9:48:34 
    *
    *┌──────────────────────────────────┐
    *│　***************************************************．　│
    *│　**********************　　　　　　　　　　　　　　│
    *└──────────────────────────────────┘
*/
    public class ActionAuthrizaFilterAttribute : Attribute, IActionFilter
    {
        private readonly string Authorization = "Authorization";
        [Autowired]
        protected ICacheTokenDictionary CacheTokenDictionary { get; set; }

        [Autowired]
        protected ILogger<ActionAuthrizaFilterAttribute> logger { get; set; }

        private  Type[] IgnoreType = new Type []{ typeof(CustomAllowAnonymousAttribute),typeof(AllowAnonymousAttribute)};
        public ActionAuthrizaFilterAttribute(ICacheTokenDictionary cacheTokenDictionary, IModelMetadataProvider modelMetadataProvider, ILogger<ActionAuthrizaFilterAttribute> _logger)
        {
            CacheTokenDictionary = cacheTokenDictionary;
            logger = _logger;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ActionDescriptor.EndpointMetadata.Any(item =>IgnoreType.Contains(item.GetType())))
            {

                return;
            }
            if (context.HttpContext.Request.Headers.ContainsKey(Authorization) && context.HttpContext.User.Claims.Where(x => x.Type == ClaimTypes.NameIdentifier).Any())
            {
                string Token = context.HttpContext.Request.Headers[Authorization];
                Token = Token.GetToken();
                int.TryParse(context.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value, out int Id);
                if (!CacheTokenDictionary.AnyToken(Id, Token))
                    context.Result = new JsonResult(new
                    {
                        status = false,
                        msg = "你的账号已在其它地方登录,如有需要请及时修改密码!",
                        code = 400,
                    });
            }
            else
            {
                context.Result = new JsonResult(new
                {
                    status = false,
                    msg = "请先登录!",
                    code = 400
                });
            }
        }
    }
}
